package com.gztms.utils;

import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Zoey
 * @date 2023/5/1 16:30
 * @Description bean拷贝工具类
 **/
public class BeanCopyUtils {

    private BeanCopyUtils() {

    }

    /**
     * 对象拷贝
     * @param source
     * @param clazz
     * @param <V>
     * @return
     */
    public static<V>  V copyBean(Object source, Class<V> clazz) {
        V result = null;
        // 1、创建目标对象
        try {
            result = clazz.newInstance();
            // 2、copy实体属性
            BeanUtils.copyProperties(source,result);

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        // 3、返回结果

        return result;

    }

    public static <T,V> List<V> copyBeanList(List<T> list, Class<V> clazz) {
       // 使用stream流进行拷贝
        return list.stream()
                .map(o -> copyBean(o, clazz))
                .collect(Collectors.toList());
    }
}
